package oop.controller.action.question;

import java.util.List;

import oop.controller.action.DefaultAction;
import oop.data.BaseQuestion;
import oop.data.Topic;
import oop.data.User;
import oop.db.dao.QuestionDAO;
import oop.db.dao.TopicDAO;
import oop.db.dao.UserDAO;
import oop.taglib.UtilFunctions;

import org.apache.commons.lang.StringUtils;

public class ListAction extends DefaultAction {

	public static final int PAGE_LENGTH = 10;

	@Override
	public void performImpl() throws Exception {
		
		title("Danh sách câu hỏi");
		
		String submit = request.getParameter("ql_submit");
		if ("delete".equals(submit)) {
			setNextAction("question.delete");
			return;
		}
		
		String pageStr = StringUtils.defaultIfEmpty(request
				.getParameter("page"), "1");
		int page = Integer.parseInt(pageStr) - 1;

		List<BaseQuestion> questions;
		long count;
		if (request.getParameter("topic") != null) {
			int id = Integer.parseInt(request.getParameter("topic"));
			questions = QuestionDAO.fetchByTopic(id, page * PAGE_LENGTH, PAGE_LENGTH);
			Topic topic = TopicDAO.fetchById(id);
			title("Danh sách các câu hỏi thuộc chủ đề " + topic.getName() + " trên website trắc nghiệm CSForce");
			count = QuestionDAO.countByTopic(id);
		} else if (request.getParameter("author") != null) {
			int id = Integer.parseInt(request.getParameter("author"));
			questions = QuestionDAO.fetchByAuthor(id, page * PAGE_LENGTH, PAGE_LENGTH);
			List<User> user = UserDAO.fetchById(id);
			title("Danh sách các đề thi do " + (user.get(0).getName()) + " đăng trên website trắc nghiệm CSForce");
			count = QuestionDAO.countByAuthor(id);
		} else {
			questions = QuestionDAO.fetch(page * PAGE_LENGTH, PAGE_LENGTH);
			count = QuestionDAO.count();
		}
		
		request.setAttribute("questions", questions);
		request.setAttribute("page", page+1);
		request.setAttribute("pageCount", UtilFunctions.ceil(count / (double)PAGE_LENGTH));
	}

}
